#ifndef _RBT_TIMER_H__INCLUDED_
#define _RBT_TIMER_H__INCLUDED_

#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include "ngx_rbtree.h"

struct timer_node_s;
typedef void (*timer_handler_pt)(struct timer_node_s*);

typedef struct timer_node_s {
    ngx_rbtree_node_t node;
    timer_handler_pt handler;
} timer_node_t;

ngx_rbtree_t timer;
static ngx_rbtree_node_t sentinel; // 静态，避免sentinel初始化


void init_timer() {
    ngx_rbtree_init(&timer, &sentinel, ngx_rbtree_insert_timer_value);
}

unsigned int current_time() {
    unsigned int now;
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC, &tp);
    now = tp.tv_sec * 1000;
    now += tp.tv_nsec / 1000000;
    return now;
}

timer_node_t* add_timer(int expire, timer_handler_pt func) {
    timer_node_t* te = (timer_node_t*)malloc(sizeof(timer_node_t));
    assert(te != NULL);
    te->node.key = expire + current_time();
    te->handler = func;
    ngx_rbtree_insert(&timer, &te->node);
    return te;
}

void del_timer(timer_node_t* tn) {
    ngx_rbtree_delete(&timer, &tn->node);
}

void handle_timer() {
    ngx_rbtree_node_t *root;
    ngx_rbtree_node_t *node;
    for (;;) {
        root = timer.root;
        if (root == timer.sentinel) {
            break;
        }
        node = ngx_rbtree_min(root, timer.sentinel);
        if (node->key > current_time()) {
            break;
        }
        
        // 触发定时任务
        timer_node_t *tn = (timer_node_t*)(void*)node;
        tn->handler(tn);
        ngx_rbtree_delete(&timer, &tn->node);
        free(tn);
    }
}

int find_nearest_timer() {
    if (timer.root == timer.sentinel) {
        return -1;
    }
    ngx_rbtree_node_t *node;
    node = ngx_rbtree_min(timer.root, timer.sentinel);
    int diff = (int)node->key - (int)current_time();
    return diff > 0 ? diff : 0;
}

#endif